/* eslint-disable react/jsx-indent */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Select, Radio, Row, Col } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import AddEmpInfor from './AddEmpInfor';
import AddMatInfor from './AddMatInfor';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
    xl: { span: 8 },
    xxl: { span: 6 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const RadioGroup = Radio.Group;
@connect(({ card: { updatedetail, coltFlag }, loading }) => ({
  updatedetail,
  coltFlag,
  loading: loading.effects['card/fetchUpdateDetail'] && loading.effects['card/updateList'],
}))
class UpdateCard extends Component {
  state = {};

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { insCardHdlId } = location.query;
    this.setState({
      tabKey: location.query.tabKey,
    });
    dispatch({
      type: 'card/fetchUpdateDetail',
      payload: { insCardHdlId },
    });
  }

  save = () => {
    const { dispatch, form, updatedetail } = this.props;
    const { insCardHdl } = updatedetail;
    const insCardHdlData = insCardHdl;
    const { tabKey } = this.state;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const matlist = [];
      const insCardHdl1 = {};
      const temp = values;
      Object.keys(temp).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(temp[key].inpType) === '9') {
            let file = '';
            if (temp[key].fileList && temp[key].fileList.length) {
              temp[key].fileList.forEach(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                } else if (!item.responss) {
                  file += item.uid
                    .concat('|')
                    .concat(item.name)
                    .concat(',');
                }
              });
            }
            temp[key].inpVal = file ? file.slice(0, file.length - 1) : '';
          }
          temp[key].pkgPageDetailId = temp[key].pageDetailId;
          matlist.push(temp[key]);
        } else if (key === 'copyFiles') {
          insCardHdl1.copyFiles = temp[key];
        } else if (key === 'masterFiles') {
          insCardHdl1.masterFiles = temp[key];
        }
      });

      insCardHdl1.matFlag = Number(tabKey) === 1 ? temp.matFlag : 1;
      insCardHdl1.insCardHdlId = insCardHdlData.insCardHdlId;
      insCardHdl1.vno = insCardHdlData.vno;
      const param = {
        matlist,
        insCardHdl: insCardHdl1,
      };

      dispatch({
        type: 'card/updateList',
        payload: param,
        callback: response => {
          if (response.success) {
            router.goBack();
          }
        },
      });
    });
  };

  close = () => {
    const { location } = this.props;
    router.push(`/socialinsurancemanagement/socialcard/index?isRenew=${location.query.isRenew}`);
  };

  onSelectData = element => {
    const { dispatch, updatedetail } = this.props;
    const { elementArr } = updatedetail;
    dispatch({
      type: 'card/matInfor',
      payload: { elementArr, element },
    });
  };

  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      Number(value.inpType) !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (Number(value.inpType) === 1 || Number(value.inpType) === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const {
      updatedetail,
      coltFlag,
      form: { getFieldDecorator },
      loading
    } = this.props;
    const { tabKey } = this.state;
    const { empSendInfoVo, empBaseInfoVo, elementArr, matFileDictItem, insCardHdl } = updatedetail;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const renderElem = ele =>
      ele && ele.length
        ? ele.map(element => (
            <Row key={element.pageDetailId}>
              <Col span={8}>
                <FormItem {...formItemLayouts} label={<span> {element.matName}</span>}>
                  {getFieldDecorator(`mat_${element.pageDetailId}`, {
                    rules: [
                      {
                        required: Number(element.reqFlag) === 1,
                        validator: this.checkElement,

                        max: max(+element.inpType),
                      },
                    ],
                    initialValue: element,
                  })(<AddMatInfor onChange={this.onSelectData} />)}
                </FormItem>
              </Col>
            </Row>
          ))
        : null;
    return (
      <PageHeaderWrapper>
        <AddEmpInfor empSendInfoVo={empSendInfoVo} empBaseInfoVo={empBaseInfoVo} />
        <div className={styles.stepsAction}>
          {String(coltFlag) === '1' && matFileDictItem && matFileDictItem.length ? (
            <Card title={<span>材料信息</span>}>
              <Form>
                <div>
                  <div>
                    <Row>
                      <Col span={8}>
                        <FormItem {...formItemLayouts} label="原件材料:">
                          {getFieldDecorator('masterFiles', {
                            rules: [
                              {
                                required: false,
                                message: '请选择原件材料',
                              },
                            ],
                            initialValue:
                              insCardHdl && insCardHdl.masterFile
                                ? insCardHdl.masterFile
                                : undefined,
                          })(
                            <HOCSelect
                              style={{ width: '100%' }}
                              mode="multiple"
                              placeholder="请选择原件材料"
                              onChange={this.aaa}
                            >
                              {matFileDictItem && matFileDictItem.length
                                ? matFileDictItem.map(options => (
                                    <Option key={options.itemCode}>{options.itemName}</Option>
                                  ))
                                : null}
                            </HOCSelect>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={8}>
                        <FormItem {...formItemLayouts} label="复印件材料:">
                          {getFieldDecorator('copyFiles', {
                            rules: [
                              {
                                required: false,
                                message: '请选择复印件材料',
                              },
                            ],
                            initialValue:
                              insCardHdl && insCardHdl.copyFile ? insCardHdl.copyFile : undefined,
                          })(
                            <HOCSelect
                              style={{ width: '100%' }}
                              mode="multiple"
                              placeholder="请选择复印件材料"
                            >
                              {matFileDictItem && matFileDictItem.length
                                ? matFileDictItem.map(options => (
                                    <Option key={options.itemCode}>{options.itemName}</Option>
                                  ))
                                : null}
                            </HOCSelect>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                  </div>
                  {renderElem(elementArr)}
                </div>
              </Form>
              {Number(tabKey) === 1 ? (
                <Form>
                  <Row>
                    <Col span={14} offset={1}>
                      <FormItem {...formItemLayouts} label="材料是否完整:">
                        {getFieldDecorator('matFlag', {
                          rules: [
                            {
                              required: true,
                              message: '请选择材料是否完整',
                            },
                          ],
                          initialValue:
                            insCardHdl && insCardHdl.matFlag ? `${insCardHdl.matFlag}` : undefined,
                        })(
                          <RadioGroup>
                            <Radio value="1">是</Radio>
                            <Radio value="2">否</Radio>
                          </RadioGroup>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              ) : null}
            </Card>
          ) : null}
        </div>

        <FooterToolbar style={{ width: '100%' }}>
          <Button onClick={() => router.goBack()}>取消</Button>
          <Button style={{ marginLeft: 8 }} type="primary" onClick={() => this.save()} loading={loading}>
            保存
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}
const UpdateCardform = Form.create()(UpdateCard);
export default UpdateCardform;
